package cn.kgc.common.config.springcache;

import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * 自定义Redis缓存管理器
 * @author kgc
 */
public class CustomizedRedisCacheManager extends RedisCacheManager {

    public CustomizedRedisCacheManager(RedisCacheWriter cacheWriter,
                                       RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /**
     * 创建Redis缓存
     * @param name must not be {@literal null}.
     * @param cacheConfig can be {@literal null}.
     * @return
     */
    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        //获得缓存的名字和过期时间  @Cacheable(cacheNames = "system:menu#-1",key = "'list'")
        //["system:menu","-1"]
        String [] array= StringUtils.delimitedListToStringArray(name,"#");
        name=array[0];

        if(array.length>1){
            Long ttl = Long.valueOf(array[1]);
            cacheConfig.entryTtl(Duration.ofMinutes(ttl));
        }

        return super.createRedisCache(name, cacheConfig);
    }
}
